import React from 'react';
import ReactDOM from 'react-dom';
import { observer } from 'mobx-react';
import { ViewResourceProps } from '.';
import moment from 'moment';
import {
  WeaDateSwitch,
  WeaInputSearch,
  WeaLocaleProvider,
} from 'ecCom';
import { Tooltip, Spin } from 'antd';
import { toJS } from 'mobx';
import { getCurrentDate } from '../../apis/resource';
import jQuery from 'jquery';
const getLabel = WeaLocaleProvider.getLabel;

if(WeaLocaleProvider.getUserLanguage() == 7 || WeaLocaleProvider.getUserLanguage() == 9 ){
  moment.locale('zh-cn');
}else{
  moment.locale('en');
}

@observer
export default class ViewResouceContainerMobile extends React.Component<ViewResourceProps, any> {

  constructor(props) {
    super(props);
    this.state = {
      scrollType: '',
      date: new Date(),
    }
    getCurrentDate({}).then(({currentDate}) => {
      this.setState({date: currentDate});
    });
  }

  componentDidUpdate(prevProps, prevState) {
    this.createHeight();
    const {cubeViewResource,Search} = this.props;
    cubeViewResource.resourceParams.bywhat='4'
    setTimeout(()=>{
      if( cubeViewResource.windowTitle != ''){
        document.title = cubeViewResource.windowTitle;
	    }
    },500);
    Search.isInnerTab = true;
  }

  componentWillReceiveProps() {
    const {cubeViewResource} = this.props;
    this.setState({date: cubeViewResource.currentdate});
    cubeViewResource.timeType = 'day';
  }

  createHeight = () => {
    const {cubeViewResource} = this.props;
    // 处理高度自适应问题
    let
      container = jQuery('.resource-container', ReactDOM.findDOMNode(this)),
      conHeight = this.props.height ? (this.props.height - 108) : container.height();
    let listHeight;
    let tab = jQuery('.resource-plan-tab', container), tabHeight = tab.height()
    if(cubeViewResource.showMoreVisible){
      tabHeight=tabHeight+40;
    }
    if (tabHeight >= (conHeight / 2)) {
      listHeight = (conHeight / 2);
      tabHeight = (conHeight / 2);
    } else {
      listHeight = conHeight - tabHeight;
    }
    cubeViewResource.updateHeight(conHeight, tabHeight, listHeight);
  }


  /*周月日组件切换回调 */
  /**
   * 说明：若日,传点前的日期，且给值movedate，若年或月则传点击后的日期，且movedate不给值
   */
  onChangeWeaDateSwitch = (type, date, range) => {
    const {cubeViewResource} = this.props;
    const {timeType} = cubeViewResource;
    type != timeType && cubeViewResource.updateTimeType(type);
    cubeViewResource.resourceId = '';
    let movedate = '';
    let bywhat = '4';
    if (typeof date != 'string' && date._d && date._i) {
      if (typeof date._d == 'string') {
        date._d = new Date(date._d);
      }
      if (typeof date._i == 'string') {
        date._i = new Date(date._i);
      }
      if (date._d.getTime() != date._i.getTime() && type == 'day') {//说明点击箭头切换日期
        if (date._d.getTime() < date._i.getTime()) {
          movedate = '-1';
        } else {
          movedate = '1';
        }
      }
    }
    switch (type) {
      case 'year':
        bywhat = '1';
        break;
      case 'month':
        bywhat = '2';
        break;
      case 'week':
        bywhat = '3';
        break;
      case 'day':
        bywhat = '4';
        break;
    }
    let currentdate;
    if (typeof date == 'string') {
      currentdate = date;
    } else if (typeof date._i == 'string') {
      currentdate = bywhat == '4' ? date._i : date._d;
    } else {
      let rightdate;
      if (date._i && date._d) {
        rightdate = bywhat == '4' ? date._i : date._d;
      } else {
        rightdate = date;
      }
      let m = rightdate.getMonth() + 1 + '';
      let d = rightdate.getDate() + '';
      if (m.length == 1) m = '0' + m;
      if (d.length == 1) d = '0' + d;
      currentdate = rightdate.getFullYear() + '-' + m + '-' + d;
    }
    this.setState({date: date});
    cubeViewResource.query({bywhat, movedate, currentdate});
  }

  getTableHeaderInfo = (timeType, date, startHour, endHour) => {
    let blockNum = 0, tableTitle = '', tableHeaders: any = [];
    if (moment.isMoment(date)) date = new Date(date.format('L'));
    let curmoment = moment(date);
      blockNum = endHour - startHour + 1
      tableTitle = curmoment.format(`M${getLabel(383373, '月')}D${getLabel(383374, '日').replace('-','')}(ddd)${getLabel(33425, '单位')}:`) + getLabel(383376, '时')
      tableTitle = this.modifyWeekName(tableTitle);
      for (startHour; startHour <= endHour; startHour++)
        tableHeaders.push(startHour);
    return {blockNum: blockNum, tableTitle: tableTitle, tableHeaders: tableHeaders}
  }

  /*周显示多语言修正 ，moment打包后中文失效*/
  modifyWeekName = (name) => {
    try{
      if(WeaLocaleProvider.getUserLanguage() == 7 || WeaLocaleProvider.getUserLanguage() == 9){
        name=name.replace("Sun","周日");
        name=name.replace("Mon","周一");
        name=name.replace("Tue","周二");
        name=name.replace("Wed","周三");
        name=name.replace("Thu","周四");
        name=name.replace("Fri","周五");
        name=name.replace("Sat","周六");
      }
    }catch(Exception){
    }
    return name;
  }

  /*创建面板使用情况的每一行得td*/
  createTdList = (resource, blockNum, rowNum) => {
    const {cubeViewResource} = this.props;
    const { duration, useMap} = cubeViewResource;
    let tdList: any = [];
    let useArray = useMap[resource.id];
    // 创建冲突的、带有提示的单元格
    let createTooltipTd = function (obj, otherProps = {},width?) {
      let {content, bgcolor, fontcolor, title} = obj;
      let style: any = {backgroundColor: bgcolor || '#AFDC9E', color: fontcolor || '#000', textAlign: 'center'};
      let td = (
        <Tooltip title={createTitle(toJS(title))} placement="bottomRight" arrowPointAtCenter={true}>
          <td className="resource-td" style={style} {...{conflict: true}} {...otherProps}>
              <div className="resource-td-modal"/>
              {content > 1 && content}
          </td>
        </Tooltip>
      );
      return td;
    };
      return this.createTdListInDay(duration, useArray, resource, createTooltipTd, rowNum, tdList);
  }

  /*创建时间类型为天时的单元格*/
  createTdListInDay(duration, useArray, room, createTooltipTd, rowNum, tdList) {
    const {cubeViewResource} = this.props;
    let {startHour, endHour} = cubeViewResource;
    let {dspunit} = cubeViewResource;
    let useBlockMap = {};//已被使用的块，数据结构：小时数:{变色的序号：{背景颜色，字体颜色，内容}，...}
    // let subNum = 1;//每小时会被分成几段
    // 生成已被占用的时间段
    useArray && useArray.forEach((obj) => {
      // 时间处理，确认序号
      if (!obj.time) return;
      let time = obj.time.split(':');
      if (time.length != 2) return;
      let hour = parseInt(time[0]), minute = parseInt(time[1]);
      let idx = duration > 0 ? Math.floor(minute / duration) : 0;
      // 找到该数据对应的存储位置。
      if (!useBlockMap[hour]) useBlockMap[hour] = {};
      let useHour = useBlockMap[hour];
      useHour[idx] = obj;
    });
    let width=(100/dspunit)+"%";
    /*创建每小时内的分隔块、即第二层td的方法*/
    let createSubTd = (hour, idx, rowNum, colNum) => {
      let startMinute = idx * duration, endMinute = startMinute + duration - 1;
      let startTime = (hour > 9 ? hour : '0' + hour) + ':' + (startMinute > 9 ? startMinute : '0' + startMinute),
        endTime = (hour > 9 ? hour : '0' + hour) + ':' + (endMinute > 9 ? endMinute : '0' + endMinute);
        // 有值则说明已被占用
        if (useBlockMap[hour] && useBlockMap[hour][idx]) {
        return createTooltipTd(useBlockMap[hour][idx], {
          itemPosition: [rowNum, colNum],
          startTime,
          endTime,
          room
        },width);
      }
      // 空时段
      return (
        <td className="resource-td" style={{width:width}} {...{itemPosition: [rowNum, colNum]}} {...{startTime, endTime, room}}>
          <div className="resource-td-modal"/>
        </td>
      );
    };

    // 生成第一层td列表
    let colNum = 0;
    for (startHour; startHour <= endHour; startHour++) {
      let subTdList: any = [];
      for (let i = 0; i < dspunit; i++) {
        subTdList.push(createSubTd(startHour, i, rowNum, colNum))
        colNum++;
      }
      let td = (
        <td>
          <table className="resource-subTable">
            <tr>{subTdList}</tr>
          </table>
        </td>
      );
      tdList.push(td);
    }
    return tdList;
  }

  getResourceItem = () => {
    const { cubeViewResource} = this.props;
    const {resourcesList, loading, startHour, endHour} = cubeViewResource;
    let dif = endHour-startHour+1;
    let fields :Array<any> = [];
    let field :Array<any> = [];
    let HH = this.refs.resourceTableBox ? this.refs.resourceTableBox['offsetHeight'] : '';
    let tableContent = (
        <table className="resource-plan-tab" style={{width:dif*30.1}}>
            <tbody>
                {!loading && (resourcesList && resourcesList.length > 0) &&
                    resourcesList.map((resources, index) => {
                        let tdList = this.createTdList(resources, 0, index);
                        return (
                            <tr className={index == 0 ? "no-border-top" : ""}>
                                {tdList}
                            </tr>
                        );
                    })
                }
            </tbody>
        </table>
    );

    resourcesList && resourcesList.map((resources,index)=>{
        field.push(                                
                 <Tooltip placement="right" title={<div  dangerouslySetInnerHTML={{ __html: resources.title }}/>} > 
                          <div className='head-item' key={index} >{resources.name}</div>
                 </Tooltip>
          );

    })
    fields.push(
      <div className='resource-table-box-head' ref='resourceTableBoxHead' key='resourceTableBoxHead' onScroll={this.onHeadScroll} style={{height: HH}}>{field}</div>,
      <div className='resource-table-box-content' key='table' ref='resourceTableBoxContent' 
        style={{height: HH,overflow: 'auto'}} onScroll={this.onscroll} >{tableContent}</div>,
    )
    return fields;
  }
  
  getTimeItem = () => {
    const {cubeViewResource} = this.props;
    const {startHour, endHour} = cubeViewResource;
    let fields:Array<any> = [];
    for(let i=startHour; i<=endHour; i++) {
      fields.push( // 时间段格
        <div className='item' key={i}>{i}</div>
      )
    }
    return fields;
  }

  tableScroll = (e) => { // 解决事件相互冲突
      if(e.target.className === 'resource-td-modal') {
        this.setState({scrollType: 'table'});
      }else if(e.target.className === 'resource-td'){
        this.setState({scrollType: 'table'});
      }else if(e.target.parentNode.parentNode.parentNode.className === 'resource-subTable' || e.target.parentNode.className === 'resource-subTable') {
        this.setState({scrollType: 'table'});        
      }else if(e.target.className === 'resource-subTable' || e.target.parentNode.parentNode.parentNode.className === 'resource-plan-tab'){
        this.setState({scrollType: 'table'});
      }else if(e.target.parentNode.parentNode.className === 'resource-table-top-content'){
        this.setState({scrollType: 'top'});
      }else if(e.target.className === 'head-item') {
        this.setState({scrollType: 'head'});
      }
  }


  onTopScroll = (e) => {
    let table = this.refs.resourceTableBoxContent;
    let topTime = this.refs.topTime;
    
    if(this.state.scrollType === 'top'){
      table['scrollLeft'] = topTime['scrollLeft'];
    }
  }

  onHeadScroll = (e) => {
    let table = this.refs.resourceTableBoxContent;
    let resourceTableBoxHead = this.refs.resourceTableBoxHead;

    if(this.state.scrollType === 'head') {
      table['scrollTop'] = resourceTableBoxHead['scrollTop'];
    }
  }

  onscroll = (e) => {
    let resourceTableBoxHead = this.refs.resourceTableBoxHead;
    let topTime = this.refs.topTime;
    let table = this.refs.resourceTableBoxContent;
    if(this.state.scrollType === 'table') {
      topTime['scrollLeft'] = table['scrollLeft']
      resourceTableBoxHead['scrollTop'] = table['scrollTop'];
    }
  }

  render() {
    const { cubeViewResource} = this.props;
    const {loading, resourcesList, timeType} = cubeViewResource;
    // 列表中使用的数据
    let {date} = this.state
    let {startHour, endHour} = cubeViewResource;
    let {blockNum, tableTitle} = this.getTableHeaderInfo(timeType, date, startHour, endHour);
 
    return (
      <div className="wea-cube-resource-con f12" style={{height: '100%'}}>
        <div className="resource-plan-top">
          {/* 资源面板的头部操作按钮 */}
          <div className="resource-plan-top-con line">
            <WeaDateSwitch currentType={'day'} onChange={this.onChangeWeaDateSwitch}
                           currentDay={this.state.date} typeList={[]}/>
          </div>
          {/* 资源面板的头部 */}
          <table className="resource-plan-tab-header">
            <tbody>
            <tr className="no-border-top">
              <th className="first align-center" style={{width:100}}>{getLabel(124947, '资源面板')}</th>
              <th colSpan={blockNum}>{tableTitle || getLabel(383375, '读取中') + '...'}</th>
            </tr>
            </tbody>
          </table>
        </div>

        <div className="resource-container-mobile">
          <div className='resource-table-mobile' ref='resourceTable' key='resourceTable' onTouchStart={(e)=>{
            this.tableScroll(e)
          }}>
              <div className='resource-table-top' ref='resourceTableTop' >
                  <div className='resource-table-top-head'>
                      <WeaInputSearch
                          value={this.state.roomName}
                          style={{display: 'inline-block',
                                  width:cubeViewResource.conditions&&cubeViewResource.conditions.length>0?170:'100%',
                                  borderRight: '1px solid #eaeaea'}}
                          placeholder={getLabel(197, '搜索') + '...'}
                          onSearchChange={v=>{
                          cubeViewResource.resourceParams['content']=v;
                          }}
                          onSearch={(v) => {
                          cubeViewResource.query({...cubeViewResource.resourceParams, content: v})
                          }}
                      />
                  </div>
                  <div className='resource-table-top-content' ref='topTime' onScroll={this.onTopScroll} >
                      <div className='table-box'>{this.getTimeItem()}</div>
                  </div>
              </div>
                  {loading && <div className="align-center" style={{marginTop: 120}}><Spin/></div>}
                  {!loading && (!resourcesList || resourcesList.length == 0) && (
                    <div className="resource-list-placeholder">
                        <i className="anticon anticon-frown" style={{marginRight:4}} />
                      {getLabel(83553, '暂无数据')}
                    </div>
                  )}
                  {!loading &&(
                    <div className='resource-table-box' ref='resourceTableBox'>
                        {this.getResourceItem()}
                    </div>
                  )}
          </div>
          {!loading && (resourcesList && resourcesList.length > 0)&&
            <div onClick={()=>{if(!cubeViewResource.showMoreVisible)return;cubeViewResource.getMore()}}  className="list-more">
              {cubeViewResource.showMoreVisible&&getLabel('83704','显示更多') }
            </div>}
        </div>
      </div>
    )
  }

}

/*创建面板的提示信息*/
const createTitle = function (titleList) {
  if (Array.isArray(titleList) && titleList.length > 0) {
    return (
      <div className="wea-resource-titletip">
        {titleList.map((meet, idx) => {
          return (
            <div>
              {meet.map((tip) => <div dangerouslySetInnerHTML={{__html: tip}}></div>)}
              {idx + 1 < titleList.length && <div className="line"/>}
            </div>
          );
        })}
      </div>
    );
  }
  return undefined;
}





